<template>
  <div class="min-h-screen bg-gray-50 pt-16">
    <!-- 为顶部导航栏留出空间 -->
    <!-- 使用全局的 AppHeader 组件 -->
    <AppHeader />

    <!-- 主要内容区域 -->
    <main class="container mx-auto px-4 py-6">
      <div class="flex flex-col lg:flex-row gap-6">
        <!-- 左侧边栏 (PC端显示) -->
        <aside class="hidden lg:block w-64 shrink-0">
          <LeftSidebar />
        </aside>

        <!-- 中间内容区 -->
        <div class="flex-1 max-w-3xl mx-auto lg:mx-0">
          <!-- 加载状态 -->
          <div
            v-if="loading"
            class="bg-white rounded-xl shadow-sm p-12 text-center"
          >
            <div
              class="inline-block animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-primary mb-4"
            ></div>
            <p class="text-gray-600">加载中...</p>
          </div>

          <!-- 错误状态 -->
          <div
            v-else-if="error"
            class="bg-white rounded-xl shadow-sm p-12 text-center"
          >
            <i class="fa fa-exclamation-circle text-4xl text-red-500 mb-4"></i>
            <p class="text-gray-600 mb-4">{{ error }}</p>
            <button
              class="bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors"
              @click="loadUserInfo"
            >
              重试
            </button>
          </div>

          <!-- 用户信息区域 -->
          <div v-else-if="userInfo" class="space-y-6">
            <!-- 个人资料头部 -->
            <div class="bg-white rounded-xl shadow-sm overflow-hidden">
              <!-- 封面图 -->
              <div
                class="h-40 bg-gradient-to-r from-primary to-purple-600 relative"
              >
                <button
                  class="absolute right-4 bottom-4 bg-white/80 backdrop-blur-sm text-gray-700 px-3 py-1 rounded-lg text-sm hover:bg-white transition-colors flex items-center space-x-1"
                >
                  <i class="fa fa-camera"></i>
                  <span>更换封面(未实现)</span>
                </button>
              </div>

              <!-- 用户信息 -->
              <div class="px-6 pb-6 md:mt-20">
                <div
                  class="flex flex-col md:flex-row -mt-16 md:items-end space-y-4 md:space-y-0 md:space-x-6"
                >
                  <!-- 头像 -->
                  <div class="flex flex-col items-center md:items-start">
                    <div
                      class="w-32 h-32 rounded-full border-4 border-white overflow-hidden"
                    >
                      <img
                        :src="getSafeAvatar(userInfo.avatar)"
                        alt="用户头像"
                        class="w-full h-full object-cover"
                      />
                    </div>
                    <button
                      class="mt-3 bg-white border border-gray-200 text-gray-700 px-3 py-1 rounded-lg text-sm hover:bg-gray-50 transition-colors hidden md:block"
                    >
                      更换头像(未实现)
                    </button>
                  </div>

                  <!-- 用户资料 -->
                  <div class="flex-1">
                    <div
                      class="flex flex-col md:flex-row md:items-center md:justify-between"
                    >
                      <div>
                        <h1 class="text-2xl font-bold text-gray-900">
                          {{ getSafeUserName(userInfo) }}
                        </h1>
                        <p class="text-gray-500">@{{ userInfo.loginId }}</p>
                      </div>
                      <button
                        class="mt-3 md:mt-0 bg-primary text-white px-4 py-2 rounded-lg hover:bg-primary/90 transition-colors"
                      >
                        编辑资料(未实现)
                      </button>
                    </div>

                    <!-- 简介 -->
                    <p class="mt-3 text-gray-700">
                      {{ userInfo.intro || "这个人很懒，没留下什么" }}
                    </p>

                    <!-- 社交链接 -->
                    <div class="flex items-center space-x-4 mt-3">
                      <a
                        href="#"
                        class="text-gray-500 hover:text-primary transition-colors"
                      >
                        <i class="fa fa-github"></i>
                      </a>
                      <a
                        href="#"
                        class="text-gray-500 hover:text-primary transition-colors"
                      >
                        <i class="fa fa-twitter"></i>
                      </a>
                      <a
                        href="#"
                        class="text-gray-500 hover:text-primary transition-colors"
                      >
                        <i class="fa fa-linkedin"></i>
                      </a>
                      <a
                        href="#"
                        class="text-gray-500 hover:text-primary transition-colors"
                      >
                        <i class="fa fa-globe"></i>
                      </a>
                    </div>

                    <!-- 统计数据 -->
                    <div class="flex items-center space-x-6 mt-4">
                      <div>
                        <span class="block text-lg font-bold text-gray-900">{{
                          userStats?.posts || "0"
                        }}</span>
                        <span class="text-sm text-gray-500">发布</span>
                      </div>
                      <div>
                        <span class="block text-lg font-bold text-gray-900">{{
                          userStats?.following || "0"
                        }}</span>
                        <span class="text-sm text-gray-500">关注</span>
                      </div>
                      <div>
                        <span class="block text-lg font-bold text-gray-900">{{
                          userStats?.followers || "0"
                        }}</span>
                        <span class="text-sm text-gray-500">粉丝</span>
                      </div>
                      <div>
                        <span class="block text-lg font-bold text-gray-900">{{
                          userStats?.collections || "0"
                        }}</span>
                        <span class="text-sm text-gray-500">收藏</span>
                      </div>
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 个人资料导航 -->
            <div class="bg-white rounded-xl shadow-sm">
              <div class="flex border-b border-gray-200">
                <button
                  class="flex-1 py-3 text-center font-medium text-primary border-b-2 border-primary"
                  @click="activeTab = 'posts'"
                >
                  动态
                </button>
                <button
                  class="flex-1 py-3 text-center font-medium text-gray-500 hover:text-gray-700"
                  @click="activeTab = 'comments'"
                >
                  评论(未实现)
                </button>
                <button
                  class="flex-1 py-3 text-center font-medium text-gray-500 hover:text-gray-700"
                  @click="activeTab = 'collections'"
                >
                  收藏(点左侧导航栏吧, 这里没实现)
                </button>
              </div>
            </div>

            <!-- 内容区域 -->
            <div v-if="activeTab === 'posts'" class="space-y-6">
              <!-- 帖子加载状态 -->
              <div
                v-if="postsLoading"
                class="bg-white rounded-xl shadow-sm p-6"
              >
                <div class="flex space-x-3">
                  <div
                    class="w-10 h-10 rounded-full bg-gray-200 animate-pulse"
                  ></div>
                  <div class="flex-1">
                    <div
                      class="h-4 bg-gray-200 rounded w-1/4 mb-2 animate-pulse"
                    ></div>
                    <div
                      class="h-4 bg-gray-200 rounded w-1/2 mb-4 animate-pulse"
                    ></div>
                    <div
                      class="h-4 bg-gray-200 rounded w-full mb-2 animate-pulse"
                    ></div>
                    <div
                      class="h-4 bg-gray-200 rounded w-full mb-2 animate-pulse"
                    ></div>
                    <div
                      class="h-4 bg-gray-200 rounded w-2/3 animate-pulse"
                    ></div>
                  </div>
                </div>
              </div>

              <!-- 帖子列表 -->
              <div v-else-if="posts.length > 0" class="space-y-6">
                <PostCard v-for="post in posts" :key="post.id" :post="post" />
              </div>

              <!-- 空状态 -->
              <div
                v-else
                class="bg-white rounded-xl shadow-sm p-12 text-center"
              >
                <i class="fa fa-file-text-o text-4xl text-gray-300 mb-3"></i>
                <h3 class="text-lg font-medium text-gray-900 mb-1">
                  暂无发布内容
                </h3>
                <p class="text-gray-500 mb-4">快去发布你的第一篇帖子吧</p>
                <router-link
                  to="/new-post"
                  class="inline-flex items-center px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors"
                >
                  <i class="fa fa-pencil mr-2"></i>发布帖子
                </router-link>
              </div>
            </div>

            <div
              v-else-if="activeTab === 'comments'"
              class="bg-white rounded-xl shadow-sm p-12 text-center"
            >
              <i class="fa fa-comment-o text-4xl text-gray-300 mb-3"></i>
              <h3 class="text-lg font-medium text-gray-900 mb-1">评论记录</h3>
              <p class="text-gray-500">查看您在社区中发表的所有评论</p>
            </div>

            <div
              v-else-if="activeTab === 'collections'"
              class="bg-white rounded-xl shadow-sm p-12 text-center"
            >
              <i class="fa fa-bookmark-o text-4xl text-gray-300 mb-3"></i>
              <h3 class="text-lg font-medium text-gray-900 mb-1">收藏记录</h3>
              <p class="text-gray-500">查看您在社区中收藏的所有内容</p>
            </div>
          </div>
        </div>

        <!-- 右侧边栏 (PC端显示) -->
        <aside class="hidden lg:block w-72 shrink-0">
          <RightSidebar />
        </aside>
      </div>
    </main>

    <!-- 底部导航栏 (移动端显示) -->
    <AppNavbar />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from "vue"
import { useRouter } from "vue-router"
import { ElMessage } from "element-plus"
import LeftSidebar from "./LeftSidebar.vue"
import RightSidebar from "./RightSidebar.vue"
import PostCard from "./PostCard.vue"
import AppHeader from "./layout/AppHeader.vue"
import AppNavbar from "./layout/AppNavbar.vue"
import { getCurrentUserInfo, logout } from "../services/userService"
import {
  getUserStats,
  getUserPosts,
  getSafeAvatar,
  getSafeUserName,
} from "../services/postService"
import type { UserInfo } from "../services/userService"
import type {
  UserStats as PostServiceUserStats,
  Post,
} from "../services/postService"

const router = useRouter()

// 标签页状态
const activeTab = ref("posts")

// 用户信息状态
const userInfo = ref<UserInfo | null>(null)
const loading = ref(false)
const error = ref<string | null>(null)

// 用户统计数据
const userStats = ref<PostServiceUserStats | null>(null)

// 帖子数据
const posts = ref<Post[]>([])
const postsLoading = ref(false)

// 加载用户信息
const loadUserInfo = async () => {
  loading.value = true
  error.value = null
  try {
    // 1. 获取用户基本信息
    const userData = await getCurrentUserInfo()
    userInfo.value = userData

    // 2. 获取用户统计数据
    const statsData = await getUserStats(userData.uid)
    userStats.value = statsData

    // 3. 获取用户发布的帖子列表
    if (activeTab.value === "posts") {
      await loadUserPosts(userData.uid)
    }
  } catch (err) {
    const errMessage = err instanceof Error ? err.message : "获取用户信息失败"
    console.error("获取用户信息失败:", err)
    error.value = errMessage
    ElMessage.error(errMessage)

    // 如果获取失败，使用本地存储的用户信息（如果有）
    const localUserInfo = localStorage.getItem("userInfo")
    if (localUserInfo) {
      try {
        userInfo.value = JSON.parse(localUserInfo)
      } catch (parseError) {
        console.error("解析本地用户信息失败:", parseError)
      }
    }
  } finally {
    loading.value = false
  }
}

// 加载用户发布的帖子列表
const loadUserPosts = async (uid: number) => {
  postsLoading.value = true
  try {
    const { data } = await getUserPosts({
      uid,
      size: 10,
    })
    posts.value = data.postRespDTOList || []
  } catch (err) {
    console.error("获取用户发布的帖子失败:", err)
    ElMessage.error("获取用户发布的帖子失败")
    posts.value = []
  } finally {
    postsLoading.value = false
  }
}

// 处理退出登录
const handleLogout = async () => {
  try {
    logout()
    ElMessage.success("退出登录成功")
    router.push("/login")
  } catch (error) {
    console.error("退出登录失败:", error)
    ElMessage.error("退出登录失败，请稍后再试")
  }
}

// 监听标签页变化
const handleTabChange = async (tab: string) => {
  activeTab.value = tab
  if (tab === "posts" && userInfo.value) {
    await loadUserPosts(userInfo.value.uid)
  }
}

// 组件挂载时加载用户信息
onMounted(() => {
  loadUserInfo()
})
</script>

<style scoped>
/* 组件特定样式 */

/* 适配顶部导航栏的间距 */
.main-content {
  padding-top: 64px; /* 为顶部导航栏留出空间 */
}

/* 修复可能的遮挡问题 */
z-index-10 {
  z-index: 10;
}

z-index-20 {
  z-index: 20;
}

z-index-30 {
  z-index: 30;
}

z-index-40 {
  z-index: 40;
}
</style>
